// pages/SCM/store/goodsAdd/goodsAdd.js
const app = getApp()
const util = require('../../../../utils/util.js')
const lbbService = require('../../../service/service.js')

Page({

  data: {
    id: '',
    isEdit: false,
    goodsList: [],
    goodsStatIds: [],
    uindex: 0,
    goodsApply: {},
    hideFlag: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      scrollHeight: app.getScrollHeight(0)
    })
    if (options.id) {
      this.setData({
        id: options.id
      });

    }
    if (options.stat) { //-1 申请按钮功能过来，0，1，2，3是从备货按钮功能过来
      this.setData({
        stat: options.stat
      });
    }
    if (options.packId) { //待确认按钮功能过来
      this.setData({
        packId: options.packId
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this
    that.toast = that.selectComponent("#toast")
    that.personalModal = that.selectComponent("#personalModal")
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    //添加物品
    if (that.data.addGoodsFlag) {
      let list = that.data.selGoodsList
      util.print('selGoodsList',list);
      for (var i = 0; i < list.length; i++) {
        that.selGoodsAdd(list[i]);
      }
      that.data.selGoodsList = [];
    } else if(that.data.maintainers&&that.data.maintainers.maintainUid){
      that.data.goodsApply.applyUserName = that.data.maintainers.maintainName;
      that.data.goodsApply.applyUserUid = that.data.maintainers.maintainUid;
      that.data.maintainers = null;
    } else if(that.data.changedLocationInfo&&that.data.changedLocationInfo.hospitalName){
      that.data.goodsApply.hospitalName = that.data.changedLocationInfo.hospitalName;
      that.data.goodsApply.hospitalId = that.data.changedLocationInfo.hospitalId;
      that.data.changedLocationInfo = null;
    } else if(that.data.selectAddress&&that.data.selectAddress.receivePerson){
      that.data.goodsApply.receivePerson = that.data.selectAddress.receivePerson;
      that.data.goodsApply.receivePhone = that.data.selectAddress.receivePhone;
      that.data.goodsApply.receiveAddress = that.data.selectAddress.receiveAddress;
      that.data.goodsApply.addressId = that.data.selectAddress.id;
      that.data.selectAddress = null;
    } else {
      that.goodsApplyItem();
      return;
    }
    that.setData({
      goodsApply:that.data.goodsApply
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  /**
   * 编辑申请
   */
  toEditApply: function(){
    this.setData({
      isEdit: true
    })
  },
  /**
   * 取消编辑
   */
  closeEdit: function(){
    this.setData({
      isEdit: false
    })
  },
  /**
   * 添加物品
   */
  toAddWarehouseGoods: function () {
    let selGoodsList = [];
    this.data.goodsApply.goodsAccessDetails.forEach(item=>{
      selGoodsList.push({goodsId:item.goodsId,goodsName:item.goods.name,addNum:item.goodsNum})
    })
    wx.navigateTo({
      url: '../chooseGoods/chooseGoods?optaction=2&selGoodsList='+JSON.stringify(selGoodsList),
    })
  },
  /**
   * 提交编辑
   */
  editApply: function(){
    util.print('editApply',this.data.goodsApply);
    let that = this;
    let goodsApply = that.data.goodsApply;
    let detailJson = [];
    for(let i=0;i<goodsApply.goodsAccessDetails.length;i++){
      if(goodsApply.goodsAccessDetails[i].goodsNum==0){
        that.toast.showToast(goodsApply.goodsAccessDetails[i].goods.name + '数量需大于零');
        return;
      }else {
        detailJson.push({goodsId:goodsApply.goodsAccessDetails[i].goodsId,goodsNum:goodsApply.goodsAccessDetails[i].goodsNum});
      }
    }
    lbbService.updateApplyInfo({
      id:goodsApply.id,
      applyUid:goodsApply.applyUid,
      hospitalId:goodsApply.hospitalId?goodsApply.hospitalId:'',
      addressId:goodsApply.addressId?goodsApply.addressId:'',
      receivePhone:goodsApply.receivePhone,
      receiveAddress:goodsApply.receiveAddress,
      receivePerson:goodsApply.receivePerson,
      detailJsonStr:JSON.stringify(detailJson),
      applyRemarks:goodsApply.applyRemarks,
    },res=>{
      wx.showToast({
        title: '编辑成功',
        duration: 2000
      })
      setTimeout(()=>{
        wx.navigateBack({
          delta:1
        })
      },2000)
    })
  },
  /**
   * 输入备注
   */
  inputRemarks: function(e){
    this.data.goodsApply.applyRemarks = e.detail.value;
  },
  /**
   * 选择医院
   */
  toChooseHospital: function () {
    wx.navigateTo({
      url: '../../../chooseHospital/chooseHospital',
    })
  },
  /**
   * 选择申请人
   */
  toSelectUser: function () {
    wx.navigateTo({
      url: '../../../chooseMaintainer/chooseMaintainer?type=2',
    })
  },
  /**
   * 选择收货地址
   */
  toChooseAddress: function () {
    wx.navigateTo({
      url: '../chooseAddress/chooseAddress',
    })
  },
  /**
   * 加减物品数量
   */
  selectGoods: function (e) {
    let that = this;
    util.print("选择物品的计数器的数量事件", e);
    let item = e.currentTarget.dataset.item;
    let idex = e.currentTarget.dataset.idex;
    let addNum = e.detail.value;
    if(idex!=undefined){
      let upDetailsList = that.data.goodsApply.goodsApplyUps[idex].upDetailsList;//该包裹的物品列表
      for (const upDetailItem of upDetailsList){
        if(upDetailItem.goodsId==item.goodsId){
          upDetailItem.deliverNum = addNum;
          break;
        }
      }
      that.data.goodsApply.goodsApplyUps[idex].upDetailsList = upDetailsList;
    }else {
      let goodsAccessDetails = that.data.goodsApply.goodsAccessDetails;
      for (const goodsItem of goodsAccessDetails){
        if(goodsItem.goodsId==item.goodsId){
          goodsItem.goodsNum = addNum;
          break;
        }
      }
      that.data.goodsApply.goodsAccessDetails = goodsAccessDetails;
    }
    
    that.setData({
      goodsApply: that.data.goodsApply,
    })
  },
  /**
   * 删除物品
   */
  deleteGoods: function (e) {
    let index = e.currentTarget.dataset.index;
    let idex = e.currentTarget.dataset.idex;
    util.print('deleteGoods',e);
    if(idex!=undefined){
      this.data.goodsApply.goodsApplyUps[idex].upDetailsList.splice(index, 1);
    }else {
      this.data.goodsApply.goodsAccessDetails.splice(index, 1);
    }
    
    this.setData({
      goodsApply: this.data.goodsApply
    });
  },

  goodsApplyItem: function () {
    let that = this;
    let goodsList = [];
    let goodsStatIds = [];
    lbbService.goodsApplyItem({
      id: this.data.id
    }, function (res) {
      let goodsApplyUps = res.data.goodsApplyUps;
      goodsApplyUps.forEach((item, i) => {
        let upDetailsList = item.upDetailsList;
        let upStrs = [];
        upDetailsList.forEach(ele => {
          upStrs.push(ele.goodsName + ' X' + ele.deliverNum);
        })
        let str = upStrs.join('、');
        item.packGoodsStrs = str;
      });
      that.setData({
        goodsApply:res.data
      })
    });
  },
  selGoodsAdd: function (selectGoods) {
    util.print('selectGoods',selectGoods);
    let goodsAccessDetails = this.data.goodsApply.goodsAccessDetails;
    let index = goodsAccessDetails.findIndex(item=>item.goodsId==selectGoods.goodsId);
    if (index > -1) {
      goodsAccessDetails[index].goodsNum=selectGoods.addNum;
    } else {
      goodsAccessDetails.push({goodsId:selectGoods.goodsId,goodsNum:selectGoods.addNum,deliverNum:0,goods:{name:selectGoods.goodsName}});
    }

    this.setData({
      goodsApply: this.data.goodsApply
    });
    this.data.addGoodsFlag = false;
  },
  goodsApplyPackageReceive: function (e) {
    let pack = e.target.dataset.pack;
    let that = this
    let param = {
      applyId: this.data.goodsApply.id,
      id: pack.id
    };
    lbbService.goodsApplyPackageReceive(param, function (res) {
      wx.showToast({
        title: '确认收货成功',
      })
      that.goodsApplyItem();
    })
  },
  closeApply: function () {
    let that = this
    let goodsApply = that.data.goodsApply;

    let modalText = '确定取消申请吗？';
    that.personalModal.showModal(modalText, function(){
      lbbService.goodsApplyInfoSave({
        id: that.data.id,
        applyStatus: 3
      }, function (res) {
        goodsApply.applyStatus = 3
        that.setData({
          goodsApply: goodsApply
        });
        wx.showToast({
          title: '关闭申请成功',
        })
      })
    });

    
  },
  recoverApply: function () {
    let that = this
    let goodsApply = that.data.goodsApply;
    lbbService.goodsApplyInfoSave({
      id: that.data.id,
      applyStatus: 0
    }, function (res) {
      goodsApply.applyStatus = 0
      that.setData({
        goodsApply: goodsApply
      });
      wx.showToast({
        title: '恢复成功',
      })

    })
  },

  toStockUp: function () {
    let that = this
    wx.navigateTo({
      url: '../goodsApplyStockUp/goodsApplyStockUp?id=' + that.data.id,
    })
  },
  previewImage: function (e) {
    var urls = e.target.dataset.src;
    wx.previewImage({
      urls: urls // 需要预览的图片http链接列表
    })
  },
  copyReceive: function (e) {
    let pack = e.target.dataset.pack;
    let goodsApply = this.data.goodsApply;
    let str = '';
    str += '申请人：' + goodsApply.applyUserName + '\n';
    if (goodsApply.receivePerson)
      str += '收货人名称：' + goodsApply.receivePerson + '\n';
    if (goodsApply.receivePhone)
      str += '收货人联系方式：' + goodsApply.receivePhone + '\n';
    if (goodsApply.receiveAddress)
      str += '收货人联系方式：' + goodsApply.receiveAddress + '\n';
    if (goodsApply.hospitalName)
      str += '医院：' + goodsApply.hospitalName + '\n';
    str += '发货物品：' + pack.packGoodsStrs + '\n';
    wx.setClipboardData({
      data: str,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功',
            })
          }
        })
      }
    })
  },
  hideModal: function () {
    this.setData({
      hideFlag: true
    });
  },
  stopMaoPao: function () {
    return true;
  },
  logisticsNameInp: function (e) {
    let val = e.detail.value;
    let pack = this.data.pack;
    pack.logisticsName = val;
    this.setData({
      pack: pack
    })
  },
  logisticsNumInp: function (e) {
    let val = e.detail.value;
    let pack = this.data.pack;
    pack.logisticsNum = val;
    this.setData({
      pack: pack
    })
  },
  //扫码获取物流编号
  scanQrCode: function () {
    let that = this
    let pack = this.data.pack;
    wx.scanCode({
      success(res) {
        pack.logisticsNum = res.result;
        that.setData({
          pack: pack
        });
      }
    })
  },
  logisticsPriceInp: function (e) {
    let num = e.detail.value;
    num = num.toString(); //先转换成字符串类型
    if (num.indexOf('.') == 0) { //第一位就是 .
      num = '0' + num
    }
    num = num.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
    num = num.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    num = num.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    num = num.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    if (num.indexOf(".") < 0 && num != "") {
      num = parseFloat(num);
    }

    let pack = this.data.pack;
    pack.logisticsPrice = num;
    this.setData({
      pack: pack
    })
  },
  /**
   * 待收货状态下支持编辑物品
   */
  editGoods: function(e){
    let pack = e.target.dataset.pack;
    this.setData({
      isEditGoods: true,
      pack: pack
    });
  },
  /**
   * 提交编辑
   */
  editGoodsSubmit: function(e){
    let that = this;
    let pack = e.currentTarget.dataset.pack;
    let goodsApply = that.data.goodsApply;
    util.print('editGoodsSubmit',goodsApply);
    lbbService.updateApplyReceivePackage({
      applyId:pack.applyId,
      id:pack.id,
      upDetailsListStr:JSON.stringify(pack.upDetailsList)
    },res=>{
      that.setData({
        isEditGoods:false
      })
      that.goodsApplyItem();
    })
  },
  /**
   * 填写物流
   */
  fillLogistics: function (e) {
    let pack = e.target.dataset.pack;
    this.setData({
      hideFlag: false,
      pack: pack
    });
  },

  logisticsSubmit: function (e) {
    let that = this;
    let formData = e.detail.value;
    lbbService.goodsApplyUpSave(formData, function (res) {
      if (res.result == 0) {
        wx.showToast({
          title: '填写成功',
        })
        that.goodsApplyItem();
        that.hideModal();
      }

    })
  },


})